package com.igeek.boot.service;

import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisCommand;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/9/5  10:29
 */
@Service
@Slf4j
public class GeoService {

    private static final String SITE_KEY = "site";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    //添加景点的位置（经纬度）
    public boolean add() {
        //封装map key就是set集合中成员名称  value就是成员的经纬度
        HashMap<Object, Point> pointHashMap = new HashMap<>();
        pointHashMap.put("惠山古镇",new Point(120.280765,31.58758));
        pointHashMap.put("灵山胜境",new Point(120.107292,31.432141));
        pointHashMap.put("常州恐龙园",new Point(120.007698,31.830046));
        pointHashMap.put("融创乐园",new Point(120.272105,31.455554));
        pointHashMap.put("湿地公园",new Point(120.326117,31.478765));
        Long count = redisTemplate.opsForGeo().add(SITE_KEY, pointHashMap);
        log.info("count:{}",count);
        return count>0;
    }

    //以当前位置获取附近的景点
    public GeoResults findByPoint(String longitude, String latitude) {
        //封装Circle对象 10公里
        Point point = new Point(Double.parseDouble(longitude), Double.parseDouble(latitude));
        Circle circle = new Circle(point, 20000);
        //GeoResults<GeoLocation<M>> radius(K key, Circle within, GeoRadiusCommandArgs args);
        RedisGeoCommands.GeoRadiusCommandArgs args
                = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeCoordinates().includeDistance().sortAscending().limit(4);
        GeoResults<RedisGeoCommands.GeoLocation<Object>> results =
                redisTemplate.opsForGeo().radius(SITE_KEY, circle, args);
        return results;
    }

    //根据指定的景点名称 来获取它附近的景点  5公里
    public GeoResults findByMember(String member) {
        //GeoResults<GeoLocation<M>> radius(K key, M member, Distance distance, GeoRadiusCommandArgs args);
        Distance distance = new Distance(15, Metrics.KILOMETERS);
        RedisGeoCommands.GeoRadiusCommandArgs args
                = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance().sortAscending().limit(2);
        GeoResults<RedisGeoCommands.GeoLocation<Object>> results =
                redisTemplate.opsForGeo().radius(SITE_KEY, member, distance, args);
        return results;

    }
}
